<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园BBS</title>
    <link rel="icon" href="../assets/QQ.ico">
    <!--element-ui的样式-->
    <link rel="stylesheet" href="../plugins/element-ui/index.css"/>
    <!-- 引入样式  -->
    <link rel="stylesheet" href="../css/list.css"/>
    <link rel="stylesheet" href="../css/base.css">
</head>

<body>
<div id="app">
    <div id="header">
        <div class="title">校园BBS系统</div>
        <div class="login" id="header-login">
            <div v-if="!isLogin">
                您尚未
                <a href="login.html">登录</a>
            </div>
            <div v-else="isLogin"
                 style="display: flex;justify-content: center;flex-direction: column; align-items: flex-start;font-size: 15px;line-height: 25px;">
                <div style="display: flex;justify-content: center;align-items: center;">头像:<img :src="userUrl" style="width: 50px;height: 50px;border-radius: 50%;margin-left: 20px"></img>
                </div>
                <div style="display: flex;justify-content: center;align-items: center;">用户名:<span
                        style="font-size: 1.5rem;color: #f56c6c;margin-left: 20px;">{{userInfo.userName}}</span></div>
                <a @click="logout" id="logout">退出登录</a>
            </div>
        </div>
    </div>
    <div class="body">
        <div class="path">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item v-for="item in topTitle" :key="item.priority"><a :href="item.url">{{item.title}}</a>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="post">
            <el-button type="primary" round size="small" @click="dialogFormVisible = true">发表帖子</el-button>
        </div>
        <div class="content">
            <div class="content-table">
                <el-table :data="tableData" border style="width: 100%">
                    <el-table-column prop="article" label="文章" style="width:60%">
                        <template slot-scope="scope">
                                <span class="title-img">
                                    <img :src="scope.row.img" alt="" class="avatar">
                                    <a @click="toPageWithParams(`${scope.row.topicId}`,`${scope.row.title}`)"
                                       class="table-title">{{scope.row.title}}</a>
                                </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="author" label="作者" style="width:25%">
                    </el-table-column>
                    <el-table-column prop="reply" label="回复" style="width:15%">
                    </el-table-column>
                </el-table>
            </div>
            <div class="content-page">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :page-sizes="[2,5, 10, 20, 50,100]" :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper" :total="passageCount"
                               :current-page="currentPage">
                </el-pagination>
            </div>
            <el-dialog title="新增话题" :visible.sync="dialogFormVisible">
                <el-form :model="addTopicForm">
                    <el-form-item label="标题" :label-width="formLabelWidth">
                        <el-input v-model="addTopicForm.title" maxlength="50" minlength="5" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item label="内容" :label-width="formLabelWidth">
                        <el-input v-model="addTopicForm.content" type="textarea" autosize :rows='2' show-word-limit
                                  maxlength="9999"></el-input>
                    </el-form-item>
                    <el-form-item label="主题头像" :label-width="formLabelWidth" style="display: flex">
                        <template>
                            <el-upload
                                    class="avatar-uploader"
                                    style="padding-left: 0"
                                    action="/common/upload"
                                    :show-file-list="false"
                                    :on-success="handleAvatarSuccess"
                                    :on-change="onChange"
                                    ref="upload"
                            >
                                <img v-if="topicUrl" :src="topicUrl" class="avatar"></img>
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </template>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button @click="clearDialogForm">清 空</el-button>
                    <el-button type="primary" @click="submitDialogForm">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</div>


<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../plugins/vue.js"></script>
<!-- 引入组件库 -->
<script src="../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../plugins/axios.min.js"></script>
<script src="../js/request.js"></script>
<script src="../api/list.js"></script>
<script src="../api/base.js"></script>
</body>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                isLogin: false,
                dialogFormVisible: false,
                formLabelWidth: '120px',
                userUrl:'',
                topicUrl: '',
                temp: '',
                pageSize: 2,
                currentPage: 1,
                passageCount: 0,
                addTopicForm: {
                    title: '',
                    content: '',
                    topicImg: ''
                },
                userInfo: {
                    userId: '',
                    userName: '',
                    head: '',
                    gender: '',
                    createTime: '',
                },
                topTitle: [
                    {
                        title: '首页',
                        url: 'index.html',
                        priority: '1'
                    },
                    {
                        title: '',
                        url: 'list.html',
                        priority: '2'
                    }
                ],
                tableData: []
            }
        },
        created() {
            this.init()
        },
        methods: {
            async init() {
                //初始化用户信息
                const userInfo = localStorage.getItem('userInfo')
                let user = JSON.parse(userInfo)
                if (user != null) {
                    this.isLogin = true
                    this.userInfo = user
                    this.userUrl = `/common/download?name=${this.userInfo.head}`
                }
                //初始化标题信息
                let boardName = localStorage.getItem("boardName")
                for (const t of this.topTitle) {
                    if (t.priority === '2') {
                        t.title = boardName
                    }
                }
                //初始化主题信息
                let boardId = localStorage.getItem("boardId")
                const params = {
                    page: this.currentPage,
                    pageSize: this.pageSize,
                }
                this.tableData = []
                await getTopicInfoApi(boardId, params).then(res => {
                    if (String(res.code) === '1') {
                        this.editTable(res.data.records)
                        this.passageCount = res.data.total
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })

            },
            async logout() {
                await logoutApi().then((res) => {
                    if (res.code === 1) {
                        localStorage.removeItem('userInfo')
                        window.location.href = 'login.html'
                    }
                })
            },
            editTable(all) {
                for (const item of all) {
                    const temp = {}
                    temp.topicId = item.id
                    temp.author = this.getUserName(item.userId).then(res => {
                        temp.author = res
                    })
                    temp.reply = this.getReplyCount(item.id).then(res => {
                        temp.reply = res
                    })
                    temp.img = `/common/download?name=${item.topicImg}`
                    temp.title = item.title

                    this.tableData.push(temp)
                }
            },
            async getUserName(userId) {
                await getUserNameApi(userId).then(res => {
                    if (String(res.code) === '1') {
                        this.temp = String(res.data)
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
                return this.temp
            },
            async getReplyCount(topicId) {
                await getReplyCountApi(topicId).then(res => {
                    if (String(res.code) === '1') {
                        this.temp = String(res.data)
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
                return this.temp
            },
            toPageWithParams(topicId, topicName) {
                if (topicId) {
                    localStorage.setItem("topicId", topicId)
                }
                if (topicName) {
                    localStorage.setItem("topicName", topicName)
                }
                window.open("detail.html", "_self")
            },
            handleSizeChange(size) {
                this.pageSize = size
                this.init()
            },
            handleCurrentChange(currentPage) {
                this.currentPage = currentPage
                this.init()
            },
            clearDialogForm() {
                this.addTopicForm.title = ''
                this.addTopicForm.content = ''
                this.topicUrl = ''
                this.addTopicForm.topicImg = ''
            },
            async submitDialogForm() {
                const data = {}
                data.title = this.addTopicForm.title
                data.content = this.addTopicForm.content
                data.userId = this.userInfo.id
                data.topicImg = this.addTopicForm.topicImg
                let boardId = localStorage.getItem("boardId")
                data.boardId = boardId
                await saveTopicApi(data).then(res => {
                    if (String(res.code) === '1') {
                        this.dialogFormVisible = false
                        this.init()
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            handleAvatarSuccess(response, file, fileList) {
                // 拼接down接口预览
                this.topicUrl = `/common/download?name=${response.data}`
                this.addTopicForm.topicImg = response.data
            },
            onChange(file) {
                if (file) {
                    const suffix = file.name.split('.')[1]
                    const size = file.size / 1024 / 1024 < 2
                    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                        this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                        this.$refs.upload.clearFiles()
                        return false
                    }
                    if (!size) {
                        this.$message.error('上传文件大小不能超过 2MB!')
                        return false
                    }
                    return file
                }
            },

        }
    })
</script>

</html>